package com.anlogic.sdk.linker.ui;

import java.util.List;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.swt.widgets.Item;

import com.anlogic.sdk.linker.MemRangeSection;

public class MemRangeSectionCellModifier implements ICellModifier {
	private LinkerViewer linkerViewer;

	private List<String> memories;

	public MemRangeSectionCellModifier(LinkerViewer linkerViewer, List<String> memories) {
		this.linkerViewer = linkerViewer;
		this.memories = memories;
	}

	@Override
	public boolean canModify(Object element, String property) {
		return true;
	}

	@Override
	public Object getValue(Object element, String property) {
		MemRangeSection m = (MemRangeSection) element;
		if (MemRangeSection.PROPERTY_MEM_NAME.equals(property)) {
			int idx = this.memories.indexOf(m.getMemoryRange());
			return Integer.valueOf((idx >= 0) ? idx : 0);
		}
		if (MemRangeSection.PROPERTY_SEC_NAME.equals(property))
			return m.getSectionName();
		return null;
	}

	@Override
	public void modify(Object element, String property, Object value) {
		if (element instanceof Item)
			element = ((Item) element).getData();
		MemRangeSection m = (MemRangeSection) element;
		if (MemRangeSection.PROPERTY_MEM_NAME.equals(property)) {
			String s = m.getMemoryRange();
			if (s.equals(value))
				return;
			Integer v = (Integer) value;
			if (v.intValue() < 0)
				v = Integer.valueOf(0);
			m.setMemoryRange(this.memories.get(v.intValue()));
		}
		if (MemRangeSection.PROPERTY_SEC_NAME.equals(property)) {
			String s = m.getSectionName();
			if (s.equals(value))
				return;
			m.setSectionName((String) value);
		}
		this.linkerViewer.modelChanged();
	}

	public void setMemories(List<String> memories) {
		this.memories = memories;
	}
}
